const WebSocket = require('ws');
const {wsf, wsfb} = require('./websocket_server.js')
const {findAvailablePort} = require('./AvailablePort.js')

const conf = {
    port: 4403,
    servers: {}
}

const subjectId = {
    全部: null,
    大学信息技术: 19,
    数字媒体基础: 16,
    数据分析: 17,
    人工智能: 18
}

function websocketServer(server_name, callBack) {
    findAvailablePort(conf.port, port => {
        conf.port = port
        console.log(
            '\x1B[44m\x1b[37m\x1b[44m %s \x1b[0m%s',
            server_name.toUpperCase(),
            ` 端口 \x1B[36m${port}\x1B[0m 可用`
        )

        const wss = new WebSocket.Server({port: port})

        conf.servers[server_name] = wss

        wsf[server_name] && wsf[server_name](wss)
        callBack && callBack(wss)
    })
}

websocketServer('test', wss => wsfb(wss, (msg, send, error) => {
    sendmsg = (data, code = 0) => {
        send({code, data})
    }
    switch (msg.type) {
        case '敬明天':
            sendmsg('向未来')
            break;
        case 'GET': 
        const subId = subjectId[msg.subject] ? `&subjectId=${subjectId[msg.subject]}` : ''
        fetch(`https://dxtk.ecnupress.com.cn/api/items/set/random?pageSize=${msg.size}${subId}`, {
            "headers": {
                // "token": recoverUnicode(msg.token)
                "token": msg.token
            }
        })
            .then(res => res.json())
            .then(data => {
                // console.log(data);
                
                send(data)
            })
        break;

        default:
            break;
    }
}))


function recoverUnicode(str) {
    let shiftedStr = "";
    for (let i = 0; i < str.length; i++) {
        let unicode = str.charCodeAt(i);
        let shiftedUnicode = unicode - 10;
        shiftedStr += String.fromCharCode(shiftedUnicode);
    }
    return shiftedStr;
}